let utils = {
  getValue(name) {
    let elements = document.getElementsByName(name);
    for (let i = 0; i < elements.length; i++) {
      if (elements[i].checked) {
        return elements[i].value;
      }
    }
  },
  addEvent(nodeList, event, handle) {
    if (nodeList.length > 0) {
      for (let i = 0; i < nodeList.length; i++) {
        nodeList[i].addEventListener(event, handle);
      }
    } else {
      nodeList.addEventListener(event, handle);
    }
  },
  removeEvent(nodeList, event, handle) {
    if (nodeList.length > 0) {
      for (let i = 0; i < nodeList.length; i++) {
        nodeList[i].removeListener(event, handle);
      }
    } else {
      nodeList.removeListener(event, handle);
    }
  },
  toggleClass(node1, node2, className) {
    if (node1.classList.value.indexOf(className) !== -1) {
      node1.classList.remove(className);
      node2.classList.add(className);
    }
    if (node2.classList.value.indexOf(className) !== -1) {
      node2.classList.remove(className);
      node1.classList.add(className);
    }
  },
  exchangeClass(node, className) {
    if (node.classList.value.indexOf(className) !== -1) {
      node.classList.remove(className);
    } else {
      node.classList.add(className);
    }
  },
  ajax(options) {
    options = options || {};
    options.type = (options.type || "POST").toUpperCase();
    options.dataType = options.dataType || "json";

    var params = JSON.stringify(options.data);

    var xhr = new XMLHttpRequest();

    var timer = setTimeout(function () {
      if (xhr.readyState !== 4) {
        xhr.abort();
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
      }
    }, options.timeout);

    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        var status = xhr.status;
        if ((status >= 200 && status < 300) || status === 304) {
          options.success && options.success(xhr.responseText, xhr.responseXML);
        } else {
          options.error && options.error(status);
        }
      }
    });
    xhr.open("POST", options.url, false);
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.send(params);
  },
  container: document.getElementById("container"),
};
